package domain

import (
	"go-weixin/common/chendb"

	"go-weixin/app/diary/model"
	"go-weixin/app/diary/rpc/internal/dao"
	"go-weixin/app/diary/rpc/internal/repo"

	"github.com/zeromicro/x/errors"
)

type DiaryDomain struct {
	diaryRepo repo.DiaryRepo
}

func NewDiaryDomain(engine chendb.ChenDb) *DiaryDomain {
	return &DiaryDomain{
		diaryRepo: dao.NewDiaryDao(engine),
	}
}

func (d DiaryDomain) DiaryAdd(userId int64, title string, content string) error {
	affected, err := d.diaryRepo.DiaryAdd(userId, title, content)
	if err != nil {
		return nil
	}
	if affected == 0 {
		return errors.New(8000, "diary插入行数0")
	}
	return nil
}

func (d DiaryDomain) DiaryUpdate(id int64, userId int64, title string, content string) error {
	affected, err := d.diaryRepo.DiaryUpdate(id, userId, title, content)
	if err != nil {
		return err
	}
	if affected == 0 {
		return errors.New(8000, "diary修改行数0")
	}
	return nil
}

func (d DiaryDomain) DiaryDelete(id int64) error {
	affected, err := d.diaryRepo.DiaryDeleteById(id)
	if err != nil {
		return err
	}
	if affected == 0 {
		return errors.New(8000, "diary删除行数0")
	}
	return nil
}

func (d DiaryDomain) DiaryList(page int64) ([]model.DiaryModel, error) {
	// 0 10
	// 10 20
	limit := 10
	offset := (page - 1) * 10
	diaryList := make([]model.DiaryModel, 0)
	err := d.diaryRepo.DiaryList(int64(limit), offset, &diaryList)
	if err != nil {
		return nil, err
	}
	return diaryList, nil
}

func (d DiaryDomain) DiaryDetail(id int64) (*model.DiaryModel, error) {
	diary := new(model.DiaryModel)
	has, err := d.diaryRepo.DiaryGetById(id, diary)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, errors.New(8000, "diary获取详细数据false")
	}
	return diary, nil
}

func (d DiaryDomain) DiaryQueryTitle(title string, page int64) ([]model.DiaryModel, error) {
	diaryList := make([]model.DiaryModel, 0)
	limit := 10
	offset := 10 * (page - 1)
	err := d.diaryRepo.DiaryLikeByTitle(title, limit, int(offset), &diaryList)
	if err != nil {
		return nil, err
	}
	return diaryList, nil
}
